<template>
  <!--display 考勤情况-->
  <div class="attendance-status">
    <div class="module-title">
      考勤情况
      <div
        class="tooltip-container"
        @mouseenter="showTooltip($event)"
        @mouseleave="hideTooltip">
        <button class="info-btn">
          <i class="el-icon-reading"></i>
        </button>
        <!-- 悬停提示框 -->
        <div
          v-show="tooltipVisible"
          class="tooltip-box"
          :style="tooltipStyle">
          {{ attendanceInfoText }}
        </div>
      </div>
    </div>
    <div class="content-container">
      <!-- 左侧环状图 -->
      <div class="chart-section">
        <div class="pie-chart" ref="attendancePieChart"></div>
        <div class="absence-label">缺勤人数：{{ absencePeople }}</div>
      </div>

      <!-- 右侧在位情况 -->
      <div class="status-section">
        <!-- 总人数卡片 -->
        <el-card class="total-card">
          <div class="card-title">总人数</div>
          <div class="card-content">{{ attendancePeople }}/{{ totalPeople }}</div>
        </el-card>

        <!-- 分组情况卡片 -->
        <div class="group-cards">
          <el-card class="group-card">
            <div class="card-title">一组</div>
            <div class="card-content">{{ groupOneAttendancePeople }}/{{ groupOneTotalPeople }}</div>
          </el-card>
          <el-card class="group-card">
            <div class="card-title">二组</div>
            <div class="card-content">{{ groupTwoAttendancePeople }}/{{ groupTwoTotalPeople }}</div>
          </el-card>
          <el-card class="group-card">
            <div class="card-title">三组</div>
            <div class="card-content">{{ groupThreeAttendancePeople }}/{{ groupThreeTotalPeople }}</div>
          </el-card>
        </div>

        <!-- 缺勤列表 -->
        <div class="absence-list">
          <div class="list-header">
            <div class="header-cell name">姓名</div>
            <div class="header-cell class">班级</div>
            <div class="header-cell reason">缺勤原因</div>
            <div class="header-cell time">缺勤时间</div>
          </div>
          <div class="list-body">
            <div v-if="loading" class="loading-overlay">
              <i class="el-icon-loading"></i>
              <p>正在加载数据...</p>
            </div>
            <div v-else-if="absenceList.length === 0" class="no-data">
              <p>暂无缺勤记录</p>
            </div>
            <div v-else class="list-content">
              <div v-for="(item, index) in absenceList" :key="index" class="list-row">
                <div class="cell name">{{ item.name }}</div>
                <div class="cell class">{{ item.classes }}</div>
                <div class="cell reason">{{ item.absence_reason }}</div>
                <div class="cell time">{{ formatDate(item.absence_time) }}</div>
              </div>
            </div>
          </div>
          <div v-if="totalPage > 1" class="page-info">
            <!-- 自动翻页，无需手动按钮和页码显示 -->
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';

export default {
  name: 'AttendanceStatus',
  data() {
    return {
      totalPeople: '0',
      attendancePeople: '0',
      attendanceRate: 0,
      absencePeople: '0',
      absenceRate: 0,
      groupOneTotalPeople: '0',
      groupOneAttendancePeople: '0',
      groupTwoTotalPeople: '0',
      groupTwoAttendancePeople: '0',
      groupThreeTotalPeople: '0',
      groupThreeAttendancePeople: '0',
      pieChart: null,
      loading: true,
      absenceList: [],
      currentPage: 1,
      pageSize: 1,
      autoScrollInterval: null,
      totalPage: 1,
      absenceTotal: 0,
      // 提示框相关
      tooltipVisible: false,
      attendanceInfoText: '',
      tooltipStyle: {
        position: 'absolute',
        top: '-280px',
        left: '50px',
        zIndex: 1000,
        width: '380px',
        height: '260px'
      }
    };
  },
  mounted() {
    // 延迟加载数据，确保 DOM 已经渲染
    setTimeout(() => {
      this.loadAttendanceInfoText();
      this.loadData();
      // 监听窗口大小变化
      window.addEventListener('resize', this.resizeChart);
      // 启动自动翻页
      this.startAutoScroll();
    }, 500);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resizeChart);
    if (this.pieChart) {
      this.pieChart.dispose();
    }
    // 清除自动翻页定时器
    if (this.autoScrollInterval) {
      clearInterval(this.autoScrollInterval);
    }
  },
  methods: {
    // 加载考勤情况说明文本
    async loadAttendanceInfoText() {
      try {
        const response = await fetch('/tltl.txt');
        if (response.ok) {
          const text = await response.text();
          // 提取"8、"后面的文本，直到下一个序号或文件结束
          const regex = /8、(.*?)(?=\s*\d+、|$)/s;
          const match = text.match(regex);
          if (match && match[1]) {
            this.attendanceInfoText = match[1].trim();
            console.log('考勤情况说明文本:', this.attendanceInfoText);
          } else {
            console.error('未找到考勤情况说明文本');
            this.attendanceInfoText = '第一百二十八条  军队单位应当建立健全考勤制度，严格执行请假销假手续。军人因事、因病请假，应当按照规定履行审批手续；未经批准不得擅自离队，不得超假不归。';
          }
        } else {
          console.error('加载考勤情况说明文本失败');
          this.attendanceInfoText = '第一百二十八条  军队单位应当建立健全考勤制度，严格执行请假销假手续。军人因事、因病请假，应当按照规定履行审批手续；未经批准不得擅自离队，不得超假不归。';
        }
      } catch (error) {
        console.error('加载考勤情况说明文本出错:', error);
        this.attendanceInfoText = '第一百二十八条  军队单位应当建立健全考勤制度，严格执行请假销假手续。军人因事、因病请假，应当按照规定履行审批手续；未经批准不得擅自离队，不得超假不归。';
      }
    },

    async loadData() {
      try {
        const response = await this.$displayapi.getAttendance();
        if (!response || !response.data) {
          throw new Error('API返回数据格式错误');
        }

        const data = response.data;
        // 更新数据，全部转为数字类型
        this.totalPeople = Number(data.totalPeople) || 0;
        this.attendancePeople = Number(data.attendancePeople) || 0;
        this.attendanceRate = Number(data.attendanceRate) || 0;
        this.absencePeople = Number(data.absencePeople) || 0;
        this.absenceRate = Number(data.absenceRate) || 0;
        this.groupOneTotalPeople = Number(data.groupOneTotalPeople) || 0;
        this.groupOneAttendancePeople = Number(data.groupOneAttendancePeople) || 0;
        this.groupTwoTotalPeople = Number(data.groupTwoTotalPeople) || 0;
        this.groupTwoAttendancePeople = Number(data.groupTwoAttendancePeople) || 0;
        this.groupThreeTotalPeople = Number(data.groupThreeTotalPeople) || 0;
        this.groupThreeAttendancePeople = Number(data.groupThreeAttendancePeople) || 0;
        this.absenceTotal = Number(data.absencePeople) || 0;

        // 初始化图表
        this.$nextTick(() => {
          this.initPieChart();
        });

        // 获取缺勤列表
        this.getAbsenceList();

      } catch (error) {
        console.error('考勤数据加载失败:', error);
        this.$message.error('加载考勤数据失败');
      }
    },

    initPieChart() {
      if (!this.$refs.attendancePieChart) return;

      if (this.pieChart) {
        this.pieChart.dispose();
      }

      this.pieChart = echarts.init(this.$refs.attendancePieChart);

      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c}%'
        },
        series: [
          {
            name: '考勤情况',
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '20',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: [
              {
                value: this.attendanceRate,
                name: '出勤率',
                itemStyle: {
                  color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: '#1a3c8f' },
                    { offset: 1, color: '#2a4da0' }
                  ])
                }
              },
              {
                value: this.absenceRate,
                name: '缺勤率',
                itemStyle: {
                  color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: '#68d8fe' },
                    { offset: 1, color: '#4ac8fe' }
                  ])
                }
              }
            ]
          }
        ]
      };

      this.pieChart.setOption(option);
    },

    resizeChart() {
      if (this.pieChart) {
        this.pieChart.resize();
      }
    },

    async getAbsenceList() {
      try {
        const response = await this.$displayapi.getAbsence({
          pageNum: this.currentPage,
          pageSize: this.pageSize
        });
        if (!response || !response.data) {
          throw new Error('API返回数据格式错误');
        }

        if (response.data.length === 0) {
          // 当前页无数据，回退到上一页
          if (this.currentPage > 1) {
            this.currentPage--;
            this.totalPage = this.currentPage;
            // 重新拉取上一页数据
            this.getAbsenceList();
            return;
          } else {
            this.absenceList = [];
            this.totalPage = 1;
            this.loading = false;
            return;
          }
        } else {
          this.absenceList = response.data;
          // 只在有数据时更新 totalPage
          if (this.currentPage > this.totalPage) {
            this.totalPage = this.currentPage;
          }
          this.loading = false;
        }
      } catch (error) {
        console.error('获取缺勤列表失败:', error);
        this.$message.error('获取缺勤列表失败');
      }
    },

    startAutoScroll() {
      // 每5秒自动翻页
      this.autoScrollInterval = setInterval(() => {
        this.currentPage++;
        this.getAbsenceList();
      }, 5000);
    },

    formatDate(dateStr) {
      if (!dateStr || dateStr.length !== 8) return dateStr;
      return `${dateStr.substring(0, 4)}-${dateStr.substring(4, 6)}-${dateStr.substring(6, 8)}`;
    },

    handlePageChange(page) {
      this.currentPage = page;
      this.getAbsenceList();
    },

    // 显示提示框
    showTooltip(event) {
      // 根据屏幕尺寸动态计算弹窗大小
      const screenWidth = window.innerWidth;
      let tooltipWidth = 380;
      let tooltipHeight = 260;

      if (screenWidth <= 480) {
        tooltipWidth = 250;
        tooltipHeight = 200;
      } else if (screenWidth <= 768) {
        tooltipWidth = 300;
        tooltipHeight = 220;
      }

      const padding = 20;

      let left = 50;
      let top = -280;

      // 检查边界并调整位置
      if (event && event.target) {
        const rect = event.target.closest('.tooltip-container').getBoundingClientRect();
        const screenHeight = window.innerHeight;

        // 如果弹窗会超出右边界，调整位置
        if (rect.left + left + tooltipWidth > screenWidth) {
          left = screenWidth - rect.left - tooltipWidth - padding;
          if (left < -rect.left + padding) {
            left = -rect.left + padding;
          }
        }

        // 如果弹窗会超出上边界，显示在下方
        if (rect.top + top < 0) {
          top = rect.height + 10;
        }

        // 如果弹窗会超出下边界，调整位置
        if (rect.top + top + tooltipHeight > screenHeight) {
          top = screenHeight - rect.top - tooltipHeight - padding;
        }
      }

      this.tooltipStyle.left = left + 'px';
      this.tooltipStyle.top = top + 'px';
      this.tooltipVisible = true;
    },

    // 隐藏提示框
    hideTooltip() {
      this.tooltipVisible = false;
    }
  }
};
</script>

<style lang="scss" scoped>
.attendance-status {
  width: 100%;
  height: 100%;
  padding: 20px;
  box-sizing: border-box;

  .module-title {
    font-size: 22px;
    color: #68d8fe;
    margin-bottom: 20px;
    font-weight: bold;
    display: flex;
    align-items: center;
    gap: 10px;

    .tooltip-container {
      position: relative;
      display: inline-block;
    }

    .info-btn {
      background: rgba(104, 216, 254, 0.2);
      border: 1px solid rgba(104, 216, 254, 0.5);
      border-radius: 4px;
      color: #68d8fe;
      cursor: pointer;
      padding: 4px 8px;
      font-size: 16px;
      transition: all 0.3s ease;
      display: flex;
      align-items: center;
      justify-content: center;

      &:hover {
        background: rgba(104, 216, 254, 0.3);
        border-color: rgba(104, 216, 254, 0.8);
        color: #ffffff;
        transform: scale(1.05);
      }

      i {
        font-size: 14px;
      }
    }

    .tooltip-box {
      background: rgba(19, 25, 47, 0.95);
      border: 1px solid rgba(104, 216, 254, 0.5);
      border-radius: 6px;
      padding: 20px 24px;
      color: #d3d6dd;
      font-size: 14px;
      line-height: 1.6;
      width: 380px;
      height: 260px;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
      backdrop-filter: blur(10px);
      word-wrap: break-word;
      white-space: normal;
      overflow-y: auto;
      display: flex;
      align-items: flex-start;
      justify-content: flex-start;
      text-align: left;

      &::before {
        content: '';
        position: absolute;
        bottom: -6px;
        left: -6px;
        width: 0;
        height: 0;
        border-left: 6px solid transparent;
        border-right: 6px solid transparent;
        border-top: 6px solid rgba(104, 216, 254, 0.5);
      }

      &::after {
        content: '';
        position: absolute;
        bottom: -5px;
        left: -5px;
        width: 0;
        height: 0;
        border-left: 5px solid transparent;
        border-right: 5px solid transparent;
        border-top: 5px solid rgba(19, 25, 47, 0.95);
      }
    }
  }

  .content-container {
    display: flex;
    height: calc(100% - 50px);
    gap: 20px;
  }

  .chart-section {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    .pie-chart {
      width: 100%;
      height: 80%;
    }

    .absence-label {
      color: #68d8fe;
      font-size: 16px;
      margin-top: 10px;
    }
  }

  .status-section {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 20px;

    .total-card {
      background-color: rgba(19, 25, 47, 0.5);
      border: 1px solid rgba(104, 216, 254, 0.5);
      border-radius: 8px;

      .card-title {
        color: #68d8fe;
        font-size: 20px;
        margin-bottom: 10px;
        text-align: center;
      }

      .card-content {
        color: #fff;
        font-size: 28px;
        text-align: center;
      }
    }

    .group-cards {
      display: flex;
      gap: 20px;

      .group-card {
        flex: 1;
        background-color: rgba(19, 25, 47, 0.5);
        border: 1px solid rgba(104, 216, 254, 0.5);
        border-radius: 8px;
        height: 88px;

        .card-title {
          color: #68d8fe;
          font-size: 20px;
          margin-bottom: 10px;
          text-align: center;
        }

        .card-content {
          color: #fff;
          font-size: 24px;
          text-align: center;
        }
      }
    }

    .absence-list {
      flex: 1;
      background-color: rgba(19, 25, 47, 0.5);
      border: 1px solid rgba(104, 216, 254, 0.5);
      border-radius: 8px;
      padding: 1px;
      margin-top: 0;
      display: flex;
      flex-direction: column;

      .list-header {
        display: flex;
        padding: 10px 0;
        border-bottom: 1px solid rgba(104, 216, 254, 0.3);
        margin-bottom: 10px;

        .header-cell {
          flex: 1;
          text-align: center;
          color: #68d8fe;
          font-weight: bold;
          font-size: 18px;

          &.name { flex: 0.7; }
          &.class { flex: 0.7; }
          &.reason { flex: 1.2; }
          &.time { flex: 1; }
        }
      }

      .list-body {
        flex: 1;
        overflow: hidden;
        position: relative;

        .loading-overlay {
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          display: flex;
          justify-content: center;
          align-items: center;
          background-color: rgba(19, 25, 47, 0.8);
          z-index: 1;

          i {
            font-size: 24px;
            color: #68d8fe;
            margin-right: 10px;
          }

          p {
            color: #d3d6dd;
            margin: 0;
          }
        }

        .no-data {
          display: flex;
          justify-content: center;
          align-items: center;
          height: 100%;
          color: #d3d6dd;
        }

        .list-content {
          .list-row {
            display: flex;
            padding: 10px 0;
            border-bottom: 1px solid rgba(104, 216, 254, 0.1);
            transition: background-color 0.3s;

            &:hover {
              background-color: rgba(104, 216, 254, 0.05);
            }

            .cell {
              flex: 1;
              text-align: center;
              color: #d3d6dd;
              font-size: 18px;
              padding: 0 5px;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;

              &.name { flex: 0.7; }
              &.class { flex: 0.7; }
              &.reason { flex: 1.2; }
              &.time { flex: 1; }
            }
          }
        }
      }
    }

    .page-info {
      padding: 10px;
      text-align: center;

      .pagination {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 10px;

        .page-text {
          color: #68d8fe;
          font-size: 13px;
        }

        .el-button {
          background-color: rgba(104, 216, 254, 0.1);
          border-color: #68d8fe;
          color: #68d8fe;

          &:hover {
            background-color: rgba(104, 216, 254, 0.2);
          }

          &:disabled {
            background-color: rgba(104, 216, 254, 0.05);
            border-color: rgba(104, 216, 254, 0.3);
            color: rgba(104, 216, 254, 0.3);
          }
        }
      }
    }
  }
}

/* 响应式设计 - 确保弹窗在小屏幕上也能正确显示 */
@media (max-width: 768px) {
  .attendance-status .tooltip-box {
    width: 300px !important;
    height: 220px !important;
    font-size: 12px !important;
    padding: 16px 20px !important;
    line-height: 1.5 !important;
  }
}

@media (max-width: 480px) {
  .attendance-status .tooltip-box {
    width: 250px !important;
    height: 200px !important;
    font-size: 11px !important;
    padding: 12px 16px !important;
  }
}
</style>
